package main

import (
	"fmt"
	ziface "zinx/Ziface"
	znet "zinx/Znet"
)

// ping test 自定义路由
type PingRouter struct {
	znet.BaseRouter
}

/*
// 重写路由方法
func (this *PingRouter) PreHandler(request ziface.IRuquest) {

	fmt.Println("Call Router PreHandler")
	_, err := request.GetConnection().GetTCPConnection().Write([]byte("before ping...\n"))
	if err != nil {
		fmt.Println("call back before err")
	}
}
*/

func (this *PingRouter) Handler(request ziface.IRuquest) {

	fmt.Println("Call Router Handler")
	//读取客户端的数据
	//打印日志
	fmt.Println("recv from client :msgid=", request.GetConnection().GetID(), "data= ", string(request.GetData()))
	err := request.GetConnection().SendMsg(200, []byte("ping....ping....ping......"))
	if err != nil {
		fmt.Println("send msg err", err)
	}
}

/*
	func (this *PingRouter) PostHandler(request ziface.IRuquest) {
		fmt.Println("Call Router PostHandler")
		_, err := request.GetConnection().GetTCPConnection().Write([]byte("after ping...\n"))
		if err != nil {
			fmt.Println("call back before err")
		}
	}
*/
type HelloRouter struct {
	znet.BaseRouter
}

func (this *HelloRouter) Handler(request ziface.IRuquest) {

	fmt.Println("Call Router Handler")
	//读取客户端的数据
	//打印日志
	fmt.Println("recv from client :msgid=", request.GetConnection().GetID(), "data= ", string(request.GetData()))
	err := request.GetConnection().SendMsg(201, []byte("Hello zinx!"))
	if err != nil {
		fmt.Println("send msg err", err)
	}
}

func beforestart(con ziface.IConnection) {
	fmt.Println("-----> DoConnectionBegin is called <-------")
	if err := con.SendMsg(202, []byte("Doconnection before")); err != nil {
		fmt.Println("DoConnectionBegin err: ", err)
	}
}

func afterstop(con ziface.IConnection) {
	fmt.Println("-----> DoConnectionLost is called <-------")
	fmt.Println("connid=", con.GetID(), "is lost....")
}

func main() {

	//1.创建一个server句柄
	s := znet.NewServer()

	s.AddRouter(0, &PingRouter{})
	s.AddRouter(1, &HelloRouter{})

	//为当前server添加对应的回调函数
	s.SetOnConnStart(beforestart)
	s.SetOnConnStop(afterstop)
	s.Serve()
	//启动Server
}
